<template>
  <div class="app-container">
    <!--查询条件表单-->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="教师编号" prop="teacherCode">
        <el-input v-model="queryParams.teacherCode" placeholder="请输入教师编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="教师编码" prop="teacherEng">
        <el-input v-model="queryParams.teacherEng" placeholder="请输入教师编码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="教师名称" prop="teacherName">
        <el-input v-model="queryParams.teacherName" placeholder="请输入教师名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="教师状态" clearable>
          <el-option v-for="dict in sys_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--按钮操作区-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermission="['school:teacher:add']"
        >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermission="['school:teacher:edit']"
        >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermission="['school:teacher:remove']"
        >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport" v-hasPermission="['school:teacher:import']"
        >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermission="['school:teacher:export']"
        >导出</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!--数据表格区-->
    <el-table v-loading="loading" :data="teacherList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="教师ID" align="center" prop="teacherId" />
      <el-table-column label="头像" align="center" prop="avatar" width="60">
        <template #default="scope">
          <img :src="prefixAvatar(scope.row.avatar)" class="user-avatar"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="教师编号" align="center" prop="teacherCode" />-->
<!--      <el-table-column label="教师编码" align="center" prop="teacherEng" />-->
      <el-table-column label="教师名称" align="center" prop="teacherName" />
      <el-table-column label="账号" align="center" prop="account" />
      <el-table-column label="性别" align="center" prop="sexStr" />
      <el-table-column label="出生日期" align="center" prop="birthDay" />
      <el-table-column label="手机号" align="center" prop="cellPhone" />
      <el-table-column label="邮箱" align="center" prop="email" width="180" />
<!--      <el-table-column label="微信号" align="center" prop="wechat" />-->
<!--      <el-table-column label="QQ号" align="center" prop="qq" />-->
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="306" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermission="['school:teacher:edit']"
          >修改</el-button
          >
          <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermission="['school:teacher:remove']"
          >删除</el-button
          >
          <el-button
              link
              type="primary"
              icon="Key"
              @click="handleResetPwd(scope.row)"
              v-hasPermission="['system:teacher:resetPwd']"
          >重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--表格分页-->
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改教师类型对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="teacherRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="教师编号" prop="teacherCode">
              <el-input-number v-model="form.teacherCode" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教师编码" prop="teacherEng">
              <el-input v-model="form.teacherEng" placeholder="请输入教师编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="教师名称" prop="teacherName">
              <el-input v-model="form.teacherName" placeholder="请输入教师名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in sys_status" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
<!--额外字段-->
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.teacherId == undefined"  label="账号" prop="account">
              <el-input v-model="form.account" placeholder="请输入登录账号" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.teacherId == undefined"  label="密码" prop="password">
              <el-input
                  v-model="form.password"
                  placeholder="请输入登录密码"
                  type="password"
                  maxlength="20"
                  show-password
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择">
                <el-option
                    v-for="dict in sys_user_sex"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDay">
              <el-date-picker
                  v-model="form.birthDay"
                  value-format="YYYY-MM-DD"
                  type="date"
                  placeholder="请选择出生日期"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="cellPhone">
              <el-input v-model="form.cellPhone" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="微信号" prop="wechat">
              <el-input v-model="form.wechat" placeholder="请输入微信号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="QQ号" prop="qq">
              <el-input v-model="form.qq" placeholder="请输入QQ号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="家庭住址" prop="address">
              <el-input v-model="form.address" placeholder="请输入家庭住址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="个人头像" >
              <el-upload
                  ref="upload"
                  class="avatar-uploader"
                  action="javascript:void(0);"
                  :show-file-list="false"
                  :auto-upload="false"
                  :on-change="onChange"
                  accept="image/*"
              >
                <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <img :src="imageUrl" class="avatar" />
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 教师导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的教师数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
                type="primary"
                :underline="false"
                style="font-size: 12px; vertical-align: baseline"
                @click="importTemplate"
            >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Teacher">
import { ref, reactive, toRefs, getCurrentInstance } from "vue";
import * as teacherApi from "@/api/school/teacherApi";
import defAva from '@/assets/images/profile.jpg';
import {prefixAvatar} from "@/utils/common";
import * as studentApi from "@/api/school/studentApi";
import {getToken} from "@/utils/token";

/** 公共变量 */
const { proxy } = getCurrentInstance();
const { sys_status, sys_user_sex } = proxy.useDict('sys_status', 'sys_user_sex');
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    teacherCode: undefined,
    teacherEng: undefined,
    teacherName: undefined,
    status: undefined,
  },
  form: {
    teacherCode: undefined,
    teacherEng: undefined,
    teacherName: undefined,
    status: 1,
    account: undefined,
    password: undefined,
    sex: undefined,
    birthDay: undefined,
    cellPhone: undefined,
    email: undefined,
    wechat: undefined,
    qq: undefined,
    address: undefined,
    remark: undefined,
    avatar: undefined
  },
  rules: {
    teacherCode: [{ required: true, message: '教师编号不能为空', trigger: 'blur' }],
    teacherEng: [{ required: true, message: '教师编码不能为空', trigger: 'blur' }],
    teacherName: [{ required: true, message: '教师名称不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
    sex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
    birthDay: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
    account: [
      { required: true, message: '账号不能为空', trigger: 'blur' },
      {
        min: 2,
        max: 20,
        message: '账号长度必须介于 2 和 20 之间',
        trigger: 'blur',
      },
    ],
    password: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      {
        min: 5,
        max: 20,
        message: '密码长度必须介于 5 和 20 之间',
        trigger: 'blur',
      },
    ],
    email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
    cellPhone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  }
})

const { queryParams, form, rules } = toRefs(data)


/** 查询表单相关变量 */
const showSearch = ref(true);


/** 表格相关变量*/
const loading = ref(true);
const teacherList = ref([]);
const total = ref(0);

/** 按钮操作区相关变量 */
const single = ref(true);
const multiple = ref(true);
const open = ref(false);
const title = ref('');
const ids = ref([]);
const imageUrl = ref(defAva);

/** 查询教师类型列表 */
function getList() {
  loading.value = true;
  teacherApi
      .listTeacher(queryParams.value)
      .then((response) => {
        teacherList.value = response.rows;
        total.value = response.total;
      })
      .finally(() => {
        loading.value = false;
      });
}
getList();


/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef');
  handleQuery();
}

/** 表单重置 */
function reset() {
  form.value = {
    teacherId: undefined,
    teacherCode: undefined,
    teacherEng: undefined,
    teacherName: undefined,
    status: 1,
    account: undefined,
    password: undefined,
    sex: undefined,
    birthDay: undefined,
    cellPhone: undefined,
    email: undefined,
    wechat: undefined,
    qq: undefined,
    address: undefined,
    remark: undefined,
    avatar: undefined,
  };
  imageUrl.value = defAva
  proxy.resetForm('teacherRef');
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加教师';
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const teacherId = row.teacherId || ids.value;
  teacherApi.getTeacher(teacherId).then((response) => {
    if(response.avatar != undefined) {
      imageUrl.value = import.meta.env.VITE_APP_BASE_API + response.avatar
    }
    form.value = response;
    open.value = true;
    title.value = '修改教师';
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const teacherIds = row.teacherId || ids.value;
  proxy.$modal
      .confirm(`是否确认删除教师ID为"${teacherIds}"的数据项？`)
      .then(() => teacherApi.deleteTeacher(teacherIds))
      .then(() => {
        getList();
        proxy.$modal.msgSuccess('删除成功');
      })
      .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
      'school/teacher/export',
      {
        ...queryParams.value,
      },
      `teacher_${new Date().getTime()}.xlsx`,
  );
}


/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.teacherId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs.teacherRef.validate((valid) => {
    if (valid) {
      if (form.value.teacherId != undefined) {
        teacherApi.updateTeacher(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        });
      } else {
        teacherApi.addTeacher(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}


/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy
      .$prompt(`请输入"${row.teacherName}"的新密码`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: '用户密码长度必须介于 5 和 20 之间',
      })
      .then(({ value }) => {
        teacherApi.resetTeacherPassword(row.teacherId, value).then((response) => {
          proxy.$modal.msgSuccess(`修改成功，新密码是：${value}`);
        });
      })
      .catch(() => {});
}

function onChange(file) {
  console.log("ddd")
  const formData = new FormData();
  formData.append('file', file.raw);
  studentApi.uploadAvatar(formData).then((response) => {
    console.log(response)
    imageUrl.value = import.meta.env.VITE_APP_BASE_API + response.fileName
    form.value.avatar = response.fileName
  })
}

/** * 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: `Bearer ${getToken()}` },
  // 上传的地址
  url: `${import.meta.env.VITE_APP_BASE_API}/school/teacher/importData`,
});

/** 导入按钮操作 */
function handleImport() {
  upload.title = '教师导入';
  upload.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download('school/teacher/importTemplate', {}, `teacher_template_${new Date().getTime()}.xlsx`);
}
/** 文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs.uploadRef.clearFiles();
  proxy.$alert(
      `<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>${response.msg}</div>`,
      '导入结果',
      { dangerouslyUseHTMLString: true },
  );
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs.uploadRef.submit();
}

</script>

<style scoped>

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.user-avatar {
  width: 40px;
  height: 40px;
  display: block;
  border-radius: 20px;
}

</style>


<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.el-form-item__label {
  font-weight: 700;
}
</style>
